﻿using System;
using System.Configuration;
using System.Diagnostics;

namespace SuperJoe.Framework.Common
{
    public static class ConfigUtil
    {
        public static object LoggerUtil { get; private set; }

        public static T GetValueOrDefault<T>(string key, T defaultValue = default(T))
        {
            T returnValue = default(T);

            if (!TryGetValue<T>(key, out returnValue))
            {
                returnValue = defaultValue;
            }

            return returnValue;
        }

        public static T GetValue<T>(string key)
        {
            var value = ConfigurationManager.AppSettings[key];
            return (T)Convert.ChangeType(value, typeof(T));
        }

        public static bool TryGetValue<T>(string key, out T outValue)
        {
            outValue = default(T);
            bool getValueSucceed = false;
            try
            {
                var value = ConfigurationManager.AppSettings[key];
                if (value != null)
                {
                    outValue = (T)Convert.ChangeType(value, typeof(T));
                    getValueSucceed = true;
                }
            }
            catch (Exception ex)
            {

            }
            return getValueSucceed;
        }

        //public static void PrintAppSettings()
        //{
        //    using (LoggerUtil.BlockInfo("开始打印appSetting配置信息", "结束打印appSetting配置信息"))
        //    {
        //        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
        //        {
        //            LoggerHelper.Info(string.Format("{0}={1}", key, ConfigurationManager.AppSettings[key]));
        //        }
        //    }
        //}
    }
}
